import { optimizeLodashImports } from '@optimize-lodash/rollup-plugin'
import commonjs from '@rollup/plugin-commonjs'
import nodeResolve from '@rollup/plugin-node-resolve'
import ts from '@rollup/plugin-typescript'
import fse from 'fs-extra'
import { defineConfig } from 'rollup'
import { terser } from 'rollup-plugin-terser'

const input = {
  index: 'src/index.ts',
  transform: 'src/transform.ts',
  helpers: 'src/helpers.ts',
  nuxt: 'src/nuxt.ts'
}

export default defineConfig({
  input,
  external: [
    '@babel/core',
    '@babel/helper-module-imports',
    '@babel/types',
    /core-js-pure/,
    'complugin',
    'estree-to-babel',
    'fast-worker',
    'lru-cache',
    'url'
  ],
  output: [
    {
      format: 'cjs',
      dir: 'dist',
      sourcemap: true,
      sourcemapExcludeSources: true,
      hoistTransitiveImports: false,
      entryFileNames: '[name].js',
      chunkFileNames: 'private/chunk-[hash].js'
    },
    {
      format: 'es',
      dir: 'dist',
      sourcemap: true,
      sourcemapExcludeSources: true,
      hoistTransitiveImports: false,
      entryFileNames: '[name].mjs',
      chunkFileNames: 'private/chunk-[hash].mjs'
    }
  ],
  plugins: [
    nodeResolve(),
    ts(),
    optimizeLodashImports(),
    commonjs(),
    extraPlugin(),
    terser({ keep_classnames: true, toplevel: true })
  ]
})

function extraPlugin() {
  let clearPromise
  return {
    name: 'extra',
    buildEnd: () => {
      clearPromise = undefined
    },
    renderStart: options => {
      return clearPromise ?? (options.dir && (clearPromise = fse.emptyDir(options.dir)))
    },
    generateBundle: (options, bundle) => {
      Object.keys(bundle)
        .filter(f => /\.d\.mts$/.test(f) || /private[\/\\].*?\.d\.ts$/.test(f))
        .forEach(f => delete bundle[f])
    }
  }
}
